package dwl.graduation.design.security;

import dwl.graduation.design.domain.Permission;
import dwl.graduation.design.domain.Role;
import dwl.graduation.design.domain.UserInfo;
import dwl.graduation.design.service.RoleService;
import dwl.graduation.design.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userService.findUserByUserName(username);
        if(Objects.isNull(userInfo)){
            throw new UsernameNotFoundException("该用户不存在");
        }
        Integer userId = userInfo.getId();
        Set<Role> roles = roleService.getUserRole(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(roles) && roles.size()>0){
            for(Role role :roles){
                String keyWord = role.getKeyword();
                list.add(new SimpleGrantedAuthority(keyWord));
                for(Permission permission: role.getPermissions()){
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
        }
        return new User(
                username,
                passwordEncoder.encode(userInfo.getPassword())
                ,list);
    }
}
